package com.infore.airsupervise.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.beardedhen.androidbootstrap.font.FontAwesome;
import com.bigkoo.pickerview.TimePickerView;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.DefaultAxisValueFormatter;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.infore.airsupervise.R;
import com.infore.airsupervise.adapter.PointAnalyzeTableAdapter;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.app.MsgConst;
import com.infore.airsupervise.app.StatusConst;
import com.infore.airsupervise.bean.AirStationE;
import com.infore.airsupervise.bean.PointAnalyzeE;
import com.infore.airsupervise.biz.StationDetailBiz;
import com.infore.airsupervise.biz.impl.StationDetailBizImpl;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.utils.DateUtil;
import com.infore.airsupervise.utils.ToastUtil;
import com.inqbarna.tablefixheaders.TableFixHeaders;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * 站点历史数据
 */
public class StationHistoryActivity extends BaseTitleBarActivity implements
        TimePickerView.OnTimeSelectListener {

    @BindView(R.id.lineChart)
    LineChart mChart;
    @BindView(R.id.scroll_table)
    TableFixHeaders scrollTable;
    @BindView(R.id.tv_startTime)
    TextView startTime;
//    @BindView(R.id.tv_endTime)
//    TextView endTime;


    private SweetAlertDialog dialog = null;
    private StationDetailBiz dataBiz;

    private PointAnalyzeTableAdapter tableAdapter = null;
    private String[] topTitle;
    private String[] leftTitle;
    private String[][] tatbleData;
    private List<ArrayList<Entry>> entryDatas = null;
    private int historyType = StatusConst.STATISTIC_DAY;
    private String startTimeStr;
    private String endTimeStr;
    private TimePickerView startTimePickerView= null;
//    private TimePickerView endTimePickerView= null;


    private String mn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_station_history);
        ButterKnife.bind(this);
        Intent it = getIntent();
        if (it != null) {
            //获取mn号
            mn = it.getStringExtra(Constants.INTENT_STR_KEY);
        }
        // 标题栏
        title.setText("历史数据");
        rightMenu.setFontAwesomeIcon(FontAwesome.FA_TABLE);

        initView();
        initChart();
        initTable();
        getStationRealData();
    }


    /**
     * 切换图表、表格
     *
     * @param view
     */
    @Override
    protected void onRightMenuClick(View view) {
        boolean isSel = rightMenu.isSelected();
        if (isSel) {
            rightMenu.setFontAwesomeIcon(FontAwesome.FA_TABLE);
            mChart.setVisibility(View.VISIBLE);
            scrollTable.setVisibility(View.INVISIBLE);
        } else {
            rightMenu.setFontAwesomeIcon(FontAwesome.FA_BAR_CHART);
            mChart.setVisibility(View.INVISIBLE);
            scrollTable.setVisibility(View.VISIBLE);
        }
        rightMenu.setSelected(!isSel);
    }

    /**
     * 初始化视图
     */
    private void initView() {
        startTimeStr = DateUtil.getCurrentDateStr(false);
        startTime.setText(startTimeStr);
        startTime.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

//        endTimeStr = DateUtil.getCurrentDateStr(false);
//        endTime.setText(endTimeStr);
//        endTime.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable editable) {
//
//            }
//        });
    }
    /**
     * 初始化时间选择
     */
    private void initDatePicker(boolean start){
        if (start) {
            Calendar startDate = Calendar.getInstance();
            startDate.add(Calendar.DAY_OF_MONTH,0);
            startTimePickerView = new TimePickerView.Builder(ctx,this)
                    .setTitleText("")
                    .setLabel("年", "月", "日", "点", "分", "秒")
                    .setType(new boolean[] {true, true, true, false, false, false})
                    .isCenterLabel(false)
                    .setDividerColor(Color.DKGRAY)
                    .setContentSize(18)
                    .setRangDate(null , startDate)
                    .setDate(startDate)
                    .setDecorView(null)
                    .build();
        } else {
//            Calendar endDate = Calendar.getInstance();
//            endDate.add(Calendar.DAY_OF_MONTH,0);
//            endTimePickerView = new TimePickerView.Builder(ctx,this)
//                    .setTitleText("")
//                    .setLabel("年", "月", "日", "点", "分", "秒")
//                    .setType(new boolean[] {true, true, true, false, false, false})
//                    .isCenterLabel(false)
//                    .setDividerColor(Color.DKGRAY)
//                    .setContentSize(18)
//                    .setRangDate(null , endDate)
//                    .setDate(endDate)
//                    .setDecorView(null)
//                    .build();
        }
    }

    @OnClick({ R.id.tv_startTime})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_startTime:
                if(startTimePickerView == null){
                    initDatePicker(true);
                }
                startTimePickerView.show(view);
                break;
//            case R.id.tv_endTime:
//                if(endTimePickerView == null){
//                    initDatePicker(false);
//                }
//                endTimePickerView.show(view);
//                break;
        }
    }

    /**
     * 初始化表格
     */
    private void initTable() {
        tableAdapter = new PointAnalyzeTableAdapter(ctx, topTitle, leftTitle, tatbleData);
        scrollTable.setAdapter(tableAdapter);
    }

    /**
     * 初始化图表
     */
    private void initChart() {
        mChart.getDescription().setEnabled(false);
        mChart.setTouchEnabled(true);
        mChart.setDragDecelerationFrictionCoef(0.9f);

        // enable scaling and dragging
        mChart.setDragEnabled(true);
        mChart.setScaleEnabled(true);
        mChart.setDrawGridBackground(false);
        mChart.setHighlightPerDragEnabled(true);
        mChart.setPinchZoom(false);


        //  setData();

        // modify the legend ...
        Legend l = mChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(true);
        l.setTextSize(8f);

        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                if (leftTitle != null) {
                    return leftTitle[(int) value];
                } else {
                    return "";
                }
            }
        });

        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setValueFormatter(new DefaultAxisValueFormatter(0));
        leftAxis.setDrawGridLines(false);
        leftAxis.setSpaceTop(25f);
        leftAxis.setGranularityEnabled(true);

        // 隐藏右边Y轴
        mChart.getAxisRight().setEnabled(false);
    }

    /**
     * 获取网络数据
     */
    private void getStationRealData() {
        if (dataBiz == null) {
            dataBiz = new StationDetailBizImpl();
        }
        dialog = new SweetAlertDialog(ctx, SweetAlertDialog.PROGRESS_TYPE)
                .setTitleText(MsgConst.HARD_LOADING)
                .setContentText(MsgConst.PLEASE_WAITING);
        dialog.setCancelable(false);
        dialog.show();
        String startTime = startTimeStr + " 00:00:00";
        String endTime = startTimeStr + " 23:59:59";
        dataBiz.sendRecentlyDataRequest(mn, startTime, endTime, requestListener);
    }

    private OnServerResponseListener<List<PointAnalyzeE>> requestListener = new OnServerResponseListener<List<PointAnalyzeE>>() {
        @Override
        public void onSucceed(List<PointAnalyzeE> result, String desc) {
            dialog.cancel();
            if (result == null || result.size() <= 0) {
                return;
            }
            if (entryDatas != null) {
                entryDatas.clear();
            }
            setData(result);

        }

        @Override
        public void onFailed(int errorCode, String title, String desc) {
            dialog.cancel();
        }
    };

    /**
     * 转换数据格式
     *
     * @param result
     */
    private void dataFormat(List<PointAnalyzeE> result) {
        if (entryDatas == null) {
            entryDatas = new ArrayList<>();
        }
        topTitle = new String[result.size()]; //表格 顶部 数据
        for (int j = 0; j < result.size(); j++) {
            PointAnalyzeE point = result.get(j);
            if (point.getVlist() != null && point.getVlist().size() > 0) {
                if (leftTitle == null) { //之初始化一次 表格左边的头部数据 和数据填充用的二维数组
                    leftTitle = new String[point.getVlist().size()];
                    tatbleData = new String[leftTitle.length][topTitle.length];
                }
                ArrayList<Entry> entryList = new ArrayList<>();  //一条数据对应的集合
                for (int i = 0; i < point.getVlist().size(); i++) {   //便利每一个因子实体类中的数据
                    PointAnalyzeE.VlistBean factor = point.getVlist().get(i);
                    if (j == 0) {
                        leftTitle[i] = factor.getTime().substring(11, 16); //左边数据只设置一次
                    }
                    tatbleData[i][j] = factor.getValue() + ""; //填充表格内的数据
                    entryList.add(new Entry(i, (float) factor.getValue(), factor.getValue()));
                }
                entryDatas.add(entryList);
            }
            topTitle[j] = point.getName(); //表格顶部数据
        }
    }

    /**
     * 设置数据
     */
    private void setData(List<PointAnalyzeE> result) {
        dataFormat(result);
        // 颜色集合
        ArrayList<Integer> colors = new ArrayList<Integer>();
        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);


        LineData data = new LineData();

        for (int i = 0; i < entryDatas.size(); i++) {
            int mColor = colors.get(i);

            LineDataSet set = new LineDataSet(entryDatas.get(i), topTitle[i]);
            set.setAxisDependency(YAxis.AxisDependency.LEFT);
            set.setColor(mColor);
            set.setCircleColor(mColor);
            set.setValueTextColor(mColor);
            set.setLineWidth(2f);
            set.setCircleRadius(2.5f);
            set.setFillAlpha(100);
            set.setFillColor(colors.get(i));
            set.setHighLightColor(Color.RED);
            set.setDrawCircleHole(true);
            set.setMode(LineDataSet.Mode.CUBIC_BEZIER);
            data.addDataSet(set);
        }
        data.setValueTextSize(9f);

        // set data
        mChart.setData(data);
        mChart.animateY(1000);
        mChart.invalidate();
        tableAdapter.updata(topTitle, leftTitle, tatbleData);
        scrollTable.scrollTo(0, 0);
    }


    /**
     * 时间选择
     * @param date
     * @param view
     */
    @Override
    public void onTimeSelect(Date date, View view) {
        System.out.println(date);
        System.out.println(view.getId());
        Calendar selector = Calendar.getInstance();
        selector.setTime(date);

        switch (view.getId()) {
            case R.id.tv_startTime:
//                Calendar calendar = Calendar.getInstance();
//                Date endDate = DateUtil.stringToDate(endTimeStr, DateUtil.FORMAT_DATE);
//                calendar.setTime(endDate);
//                if(calendar.compareTo(selector) != 1 ){
//                    ToastUtil.showShort(ctx,"开始时间不能大于结束时间");
//                    return ;
//                }
                leftTitle = null;
                startTimeStr = DateUtil.getStringByFormat(date,DateUtil.FORMAT_DATE);
                startTime.setText(startTimeStr);
                getStationRealData();
                break;
//            case R.id.tv_endTime:
//                Calendar startCalendar = Calendar.getInstance();
//                Date startDate = DateUtil.stringToDate(startTimeStr, DateUtil.FORMAT_DATE);
//                startCalendar.setTime(startDate);
//                if(selector.compareTo(startCalendar) != 1 ){
//                    ToastUtil.showShort(ctx,"开始时间不能大于结束时间");
//                    return ;
//                }
//                leftTitle = null;
//                endTimeStr = DateUtil.getStringByFormat(date,DateUtil.FORMAT_DATE);
//                endTime.setText(endTimeStr);
//                getStationRealData();
//                break;
        }
    }
}
